package com.security.config.filter;

import com.alibaba.fastjson.JSON;
import com.security.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class CoStomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event)
            throws IOException, ServletException {
        HttpServletResponse response =event.getResponse();
        HttpServletRequest request = event.getRequest();
        if(StringUtils.isNotEmpty(request.getHeader("X-Requested-With").toString()) && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString())){
            log.info("-----------AJAX SESSION 过期处理-----------");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(
                    JSON.toJSONString(R.error(5001,"已在另外一台电脑或浏览器登录，被迫下线")));
        }else {
            log.info("-----------页面跳转 SESSION 过期处理-----------");
            response.sendRedirect("/security/login?type=2");
        }
    }
}
